package com.souku.finance.application.ui.more;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.souku.finance.application.R;
import com.souku.finance.application.base.BaseActivity;
import com.souku.finance.application.bean.VersionBean;
import com.souku.finance.application.http.retrofit.RetrofitUtils;
import com.souku.finance.application.ui.MainActivity;
import com.souku.finance.application.ui.VersionNewActivity;
import com.souku.finance.application.utils.JsonUtil;
import com.souku.finance.application.utils.level.LogUtils;
import com.souku.finance.application.utils.level.SystemUtils;
import com.souku.finance.application.widget.MyRelativeLayout;

import java.io.IOException;
import java.util.HashMap;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.onekeyshare.OnekeyShare;
import cn.sharesdk.onekeyshare.OnekeyShareTheme;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static android.R.attr.permission;

/**
 * Created by Android on 2016/12/22.
 */

public class AboutUsActivity extends BaseActivity implements View.OnClickListener {

    protected RelativeLayout topBack;
    protected TextView topTitle;
    protected RelativeLayout rlShare;
    protected RelativeLayout rlRecommend;
    protected RelativeLayout rlEncourage;
    protected RelativeLayout rlVersions;

    @Override
    public void internet() {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        super.setContentView(R.layout.act_aboutus);
        initView();
        topTitle.setText("关于首库");
    }

    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.top_back) {
            finish();
        } else if (view.getId() == R.id.rl_recommend) {
            showPopwindow();
        } else if (view.getId() == R.id.rl_encourage) {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setData(Uri.parse("market://details?id=" + getPackageName()));
            startActivity(intent);
//            Intent intent = new Intent(Intent.ACTION_VIEW);
//            intent.setData(Uri.parse("market://search?q=pub:YourPublisher Name"));
//            startActivity(intent);
        } else if (view.getId() == R.id.rl_versions) {
            getNewVersion();
        }
    }

    public void getNewVersion() {
        RetrofitUtils.create().getNewVersion().enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    String json = response.body().string();
                    if (!TextUtils.isEmpty(json)) {
                        VersionBean versionBean = JsonUtil.fastBean(JsonUtil.getData(json).toString(), VersionBean.class);
                        String currentVersionCode = SystemUtils.getVersionCode(AboutUsActivity.this);
                        if (versionBean.getVersionCode() > Integer.parseInt(currentVersionCode)) {
                            //有新版本
                            Intent intent = new Intent(AboutUsActivity.this, VersionNewActivity.class);
                            startActivity(intent);
                        } else {
                            Toast.makeText(AboutUsActivity.this, "未发现最新版本", Toast.LENGTH_LONG).show();
                        }
                    } else {
                        Toast.makeText(AboutUsActivity.this, "未发现最新版本", Toast.LENGTH_LONG).show();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {

            }
        });
    }

    private void initView() {
        topBack = (RelativeLayout) findViewById(R.id.top_back);
        topBack.setOnClickListener(AboutUsActivity.this);
        topTitle = (TextView) findViewById(R.id.top_title);
        rlShare = (RelativeLayout) findViewById(R.id.rl_share);
        rlRecommend = (RelativeLayout) findViewById(R.id.rl_recommend);
        rlRecommend.setOnClickListener(AboutUsActivity.this);
        rlEncourage = (RelativeLayout) findViewById(R.id.rl_encourage);
        rlEncourage.setOnClickListener(AboutUsActivity.this);
        rlVersions = (RelativeLayout) findViewById(R.id.rl_versions);
        rlVersions.setOnClickListener(AboutUsActivity.this);
    }

    public void showPopwindow() {
        // 利用layoutInflater获得View
        LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view = inflater.inflate(R.layout.pop_share, null);
        MyRelativeLayout rlWxq = (MyRelativeLayout) view.findViewById(R.id.rl_wxq);
        MyRelativeLayout rlWx = (MyRelativeLayout) view.findViewById(R.id.rl_wx);
        MyRelativeLayout rlQq = (MyRelativeLayout) view.findViewById(R.id.rl_qq);
        MyRelativeLayout rlXl = (MyRelativeLayout) view.findViewById(R.id.rl_xl);
        rlWxq.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showShare(AboutUsActivity.this, "WechatMoments", true);
            }
        });
        rlWx.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showShare(AboutUsActivity.this, "Wechat", true);
            }
        });
        rlQq.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showShare(AboutUsActivity.this, "QQ", true);
            }
        });
        rlXl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showShare(AboutUsActivity.this, "SinaWeibo", true);
            }
        });
        // 下面是两种方法得到宽度和高度 getWindow().getDecorView().getWidth()
        PopupWindow popupWindow = new PopupWindow(view, WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);
        // 设置popWindow弹出窗体可点击，这句话必须添加，并且是true
        popupWindow.setFocusable(true);
        // 实例化一个ColorDrawable颜色为半透明
        ColorDrawable colorDrawable = new ColorDrawable(0x30ffffff);
        popupWindow.setBackgroundDrawable(colorDrawable);
        // 设置popWindow的显示和消失动画
        popupWindow.setAnimationStyle(R.style.mypopwindow_anim_style);
        // 在底部显示
        popupWindow.showAtLocation(rlShare, Gravity.BOTTOM, 0, 0);
        // 这里检验popWindow里的button是否可以点击
    }


    /**
     * 演示调用ShareSDK执行分享
     *
     * @param context
     * @param platformToShare 指定直接分享平台名称（一旦设置了平台名称，则九宫格将不会显示）
     * @param showContentEdit 是否显示编辑页
     */
    public static void showShare(Context context, String platformToShare, boolean showContentEdit) {
        OnekeyShare oks = new OnekeyShare();
        oks.setSilent(!showContentEdit);
        if (platformToShare != null) {
            oks.setPlatform(platformToShare);
        }
        //ShareSDK快捷分享提供两个界面第一个是九宫格 CLASSIC  第二个是SKYBLUE
        oks.setTheme(OnekeyShareTheme.CLASSIC);
        // 令编辑页面显示为Dialog模式
        oks.setDialogMode();
        // 在自动授权时可以禁用SSO方式
        oks.disableSSOWhenAuthorize();
        //oks.setAddress("12345678901"); //分享短信的号码和邮件的地址
        oks.setTitle("首库金融");
        //http://192.168.23.1:8080/app/index.html
//        String appUrl = Request.HOST + "app/index.html";
        String appUrl = "https://api.91skjr.com";
        oks.setTitleUrl(appUrl);
        oks.setText("首库金融理财，注册即享888体验金、500红包、1.88%加息券、利率15%+++。");
//        oks.setImagePath("/sdcard/test-pic.jpg");  //分享sdcard目录下的图片(必须存在)
        oks.setImageUrl("https://api.91skjr.com/file/icon.png");
        oks.setUrl(appUrl); //微信不绕过审核分享链接
        //oks.setFilePath("/sdcard/test-pic.jpg");  //filePath是待分享应用程序的本地路劲，仅在微信（易信）好友和Dropbox中使用，否则可以不提供
        oks.setComment("首库金融理财，注册即享888体验金、500红包、1.88%加息券、利率15%+++。"); //我对这条分享的评论，仅在人人网和QQ空间使用，否则可以不提供
        oks.setSite("首库金融");  //QZone分享完之后返回应用时提示框上显示的名称
        oks.setSiteUrl(appUrl);//QZone分享参数
        oks.setVenueName("首库金融");
        oks.setVenueDescription("首库金融理财，注册即享888体验金、500红包、1.88%加息券、利率15%+++。");
        // 将快捷分享的操作结果将通过OneKeyShareCallback回调
        oks.setCallback(new OneKeyShareCallback());
        // 去自定义不同平台的字段内容
        //oks.setShareContentCustomizeCallback(new ShareContentCustomizeDemo());

        // 在九宫格设置自定义的图标
//        Bitmap logo = BitmapFactory.decodeResource(context.getResources(), R.drawable.ic);
//        String label = "怪盗魔术";
//        View.OnClickListener listener = new View.OnClickListener() {
//            public void onClick(View v) {
//                Log.e(">>>>>>>>>>>>", v.getId() + ">>");
//            }
//        };
//        oks.setCustomerLogo(logo, label, listener);

        // 为EditPage设置一个背景的View
        //oks.setEditPageBackground(getPage());
        // 隐藏九宫格中的新浪微博
        // oks.addHiddenPlatform(SinaWeibo.NAME);

        // String[] AVATARS = {
        // 		"http://99touxiang.com/public/upload/nvsheng/125/27-011820_433.jpg",
        // 		"http://img1.2345.com/duoteimg/qqTxImg/2012/04/09/13339485237265.jpg",
        // 		"http://diy.qqjay.com/u/files/2012/0523/f466c38e1c6c99ee2d6cd7746207a97a.jpg",
        // 		"http://diy.qqjay.com/u2/2013/0422/fadc08459b1ef5fc1ea6b5b8d22e44b4.jpg",
        // 		"http://img1.2345.com/duoteimg/qqTxImg/2012/04/09/13339510584349.jpg",
        // 		"http://diy.qqjay.com/u2/2013/0401/4355c29b30d295b26da6f242a65bcaad.jpg" };
        // oks.setImageArray(AVATARS);              //腾讯微博和twitter用此方法分享多张图片，其他平台不可以

        // 启动分享
        oks.show(context);
    }

    public static class OneKeyShareCallback implements PlatformActionListener {

        @Override
        public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
            LogUtils.e("OneKeyShareCallback = " + platform.getName() + "分享成功");
        }

        @Override
        public void onError(Platform platform, int i, Throwable throwable) {

        }

        @Override
        public void onCancel(Platform platform, int i) {
            LogUtils.e("OneKeyShareCallback = " + platform.getName() + "分享取消");
        }
    }
}
